import re
from pathlib import Path

from apps.pdd.pdd.utils.app.core.app_login import *

SID = [24082, 30713, 72425, 72427]


class AppAutoLogin(AppLogin):

    def __init__(self, platform="dy", **kwargs):
        super().__init__(**kwargs)
        self.platform = platform
        if self.platform == "dy":
            self.dy_token = self.login_dy()
            self.get_money_from_dy()
            self.get_phone = self.get_phone_from_dy
            self.get_phone_code = self.get_phone_sms_code_from_dy
        elif self.platform == "hz":
            self.hz_token = self.login_hz()
            self.get_money_from_hz()
            self.get_phone = self.get_phone_from_hz
            self.get_phone_code = self.get_phone_sms_code_from_hz
            self.sid = random.choice(SID)

    def login_dy(self, username="wkaanig", password="123TMD456"):
        cache_data = Path("/tmp/dy.json")
        if cache_data.exists():
            return json.loads(cache_data.read_text())["token"]
        url = f"http://api.dyjiema.com/zc/data.php?code=signIn&user={username}&password={password}"
        token = requests.get(url).text
        cache_data.write_text(json.dumps({"token": token}), encoding="utf-8")
        return token

    def get_money_from_dy(self):
        url = f"http://api.dyjiema.com/zc/data.php?code=leftAmount&token={self.dy_token}"
        logger.info(f"dy接码可用余额【{requests.get(url).text}】")
        return

    def get_phone_from_dy(self):
        url = f"http://api.dyjiema.com/zc/data.php?code=getPhone&token={self.dy_token}&province=河南&cardType=全部"
        phone = requests.get(url).text
        logger.debug(f"dy接码获取到号码:{phone}")
        return phone

    def get_phone_sms_code_from_dy(self, phone, keywords="拼多多"):
        for i in range(10):
            # 最多重试 20次
            url = (
                f"http://api.dyjiema.com/zc/data.php?code=getMsg&token={self.dy_token}&phone={phone}&keyWord={keywords}"
            )
            response = requests.get(url).text
            logger.debug(f"dy接码获取验证码:{phone} -> {response}")
            if "验证码是******" in response:
                raise Exception("验证码短信被屏蔽")
            if re.findall(r"验证码是(\d+)", response):
                return re.findall(r"验证码是(\d+)", response)[0]
            else:
                time.sleep(5)
        else:
            logger.debug("我重试完了 没有收到验证码")
            raise Exception("我重试完了 没有收到验证码")

    def login_hz(self):
        username = "dfee0871ca2da590eb8068c3493b6e69695647e2ec1d0f195921060810d0571c"
        password = "3cfdf79d69b36f65980d41a19341ce128f0cb79c9b9660a0c672fa1023651a23"
        cache_data = Path("/tmp/hz.json")
        if cache_data.exists():
            return json.loads(cache_data.read_text())["token"]
        url = f"https://api.haozhuma.com/sms/?api=login&user={username}&pass={password}"
        token = requests.get(url).json()["token"]
        cache_data.write_text(json.dumps({"token": token}), encoding="utf-8")
        return token

    def get_money_from_hz(self):
        url = f"https://api.haozhuma.com/sms/?api=getSummary&token={self.hz_token}"
        logger.info(f"hz接码可用余额【{requests.get(url).json()['money']}】")
        return

    @retry(stop_max_attempt_number=30, wait_fixed=1000)
    def get_phone_from_hz(self):
        url = f"https://api.haozhuma.com/sms/?api=getPhone&token={self.hz_token}&sid={self.sid}"
        resp = requests.get(url).json()
        phone = resp.get("phone")
        logger.debug(f"hz接码获取到号码:{phone} {resp}")
        if not phone:
            time.sleep(5)
            raise Exception("获取不到新号码了")
        return phone

    def get_phone_sms_code_from_hz(self, mobile):
        for i in range(10):
            # 最多重试 20次
            url = f"https://api.haozhuma.com/sms/?api=getMessage&token={self.hz_token}&sid={self.sid}&phone={mobile}&tm={int(time.time() * 1000)}"
            response = requests.get(url).json()
            logger.debug(f"hz接码获取验证码:{mobile} -> {response}")
            if str(response.get("code")) == "0":
                return response.get("yzm")
            else:
                time.sleep(5)
        else:
            logger.debug("我重试完了 没有收到验证码")
            raise Exception("我重试完了 没有收到验证码")

    def run_input(self, mobile, input_sms_code=False):
        for _ in range(3):
            if input_sms_code:
                sms_code = input("请输入验证码:")
            else:
                sms_code = self.get_phone_code(mobile)
            result = self.verify_sms_code(mobile, sms_code)
            if result.get("code") == 200:
                return result
            elif result.get("error_code") == 40006:
                raise Exception(result)

    def run_auto(self, not_mobile_list=None, mobile=None):
        if not_mobile_list is None:
            not_mobile_list = []
        input_sms_code = False
        if mobile is None:
            for i in range(10):
                mobile = self.get_phone()
                if mobile not in not_mobile_list:
                    break
                else:
                    time.sleep(5)
                    continue
        else:
            input_sms_code = True
        if not mobile:
            raise Exception("获取不到新号码了")
        self.run_send(mobile)
        result = self.run_input(mobile, input_sms_code)
        logger.info(result)
        return result


if __name__ == "__main__":
    AppAutoLogin(platform="dy").run_auto(mobile="16584366365")
